package com.modul.simpleLock.testlock;

import com.modul.simpleLock.lockservice.RedisLock;
import com.modul.simpleLock.lockservice.SimpleRedisLock;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: sijunqiang
 * @Date: 2020/6/6 12:01
 * @Description: 测试简单的分布式锁的实现
 */
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class LockJobTest {


    private final StringRedisTemplate redisTemplate;


    // 每个10s 执行一次
    @Scheduled(cron = "0/10 * * * * ?")
    public void getLock() {
        String key = "demo";
        // 创建对象
        RedisLock lock = new SimpleRedisLock(redisTemplate, key);
        // 获取锁 并设置自动失效时间为30s
        Boolean isLock = lock.tryLock(20);
        if (!isLock) {
            log.info("获取锁失败，停止定时任务的");
            return;
        }
        try {
            log.info("获取锁成功,并且开始执行任务 .....");
            // 模拟获取该锁的进程 耗时
            Thread.sleep(2000);
        } catch (Exception e) {
            log.error("执行任务异常：[{}]", e.getMessage());
        } finally {
            // 释放锁
            lock.unlock();
            log.info("释放锁");
        }
    }


    // 每隔5s 执行一次
    @Scheduled(cron = "0/5 * * * * ?")
    public void test(){
        getLock();
    }
}
